package com.platform.modules.wallet.service.impl;

import cn.hutool.core.date.DateUtil;
import com.platform.common.web.service.impl.BaseServiceImpl;
import com.platform.modules.wallet.dao.WalletDao;
import com.platform.modules.wallet.domain.Wallet;
import com.platform.modules.wallet.enums.IdentityStatusEnum;
import com.platform.modules.wallet.enums.WalletStatusEnum;
import com.platform.modules.wallet.service.WalletService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service("walletService")
public class WalletServiceImpl extends BaseServiceImpl<Wallet> implements WalletService {


    @Resource
    private WalletDao walletDao;

    @Autowired
    public void setBaseDao() {
        super.setBaseDao(walletDao);
    }


    @Override
    public Wallet createWallet(Long userId) {

        Wallet wallet = getBean();
        wallet.setUserId(userId);
        this.add(wallet);
        return wallet;
    }

    @Override
    public Wallet getWallet(Long userId) {

        Wallet wallet = getById(userId);
        if (wallet == null){
            wallet = createWallet(userId);
        }
        return wallet;
    }

    @Override
    public void add(Integer amount, Long userId) {
        Wallet wallet = getById(userId);
        wallet.setAmount(wallet.getAmount() + amount.intValue());
        wallet.setUpdateTime(DateUtil.date());
        updateById(wallet);
    }

    @Override
    public void subtract(Integer amount, Long userId) {
        Wallet wallet = getById(userId);
        wallet.setAmount(wallet.getAmount() - amount.intValue());
        wallet.setUpdateTime(DateUtil.date());
        updateById(wallet);
    }

    private Wallet getBean(){

        Wallet wallet = new Wallet();
        wallet.setAmount(0);
        wallet.setBalance(0);
        wallet.setStatus(WalletStatusEnum.NORMAL.getCode());
        wallet.setCreateTime(DateUtil.date());
        wallet.setIdentityStatus(IdentityStatusEnum.NO);
        return wallet;
    }
}
